const api = require('../../utils/interface.js')
const app = getApp()
const math = require('../../utils/math.js')
Component({
  properties: {
    userInfo: null,
    typeR: {
      type: Number,
      value: '1',
    }
  },
  data: {
    statusBarHeight: wx.getSystemInfoSync()['statusBarHeight'],
    station: {},
    type_index: 0,
    money_index: 0,
    moneyList: [1000, 2000, 3000],
    productId: "",
    rechargeActivity: {}, // 充值的活动优惠
    discount: 0,
    bok: true,
    distanceInfo: {
      lat: '',
      lot: ''
    },
    couponIds: [],
    accountStoreCount: 0,
    cutPrice: 0,
    isIphoneX: false,
    state: 1,
    text: "",
    serviceCardDTOList: [],
    memberCardId:"",
    memberCardProductId:""
  },
  methods: {
    // 暂不充值
    no_recharge() {
      this.triggerEvent("traCheckedNum", 'checkeddata')
    },
    // 获取会员在降价格
    getRechargeMenberCupPrice(storeId, productId, amount) {
      let price = math.times(amount, 100)
      api.getRechargeMenberCupPrice({
        storeId: storeId,
        memberId: this.data.userInfo?this.data.userInfo.id:"",
        productId: productId,
        amount: price
      }).then(res => {
        this.setData({
          cutPrice: res.data.result
        })
      })
    },
    // 有门店id 就去请求门店id 否则请求距离最近的油站
    drivingDistance() {
      let that = this
      wx.getLocation({
        type: 'wgs84',
        success(res) {
          that.data.distanceInfo.lat = res.latitude
          that.data.distanceInfo.lot = res.longitude
          if (that.data.userInfo&&that.data.userInfo.firstMemberInfoCardDTO) {
            api.getStoreOnMemberHome({
              lat: res.latitude,
              lot: res.longitude,
              id: that.data.userInfo.firstMemberInfoCardDTO.stationId ? that.data.userInfo.firstMemberInfoCardDTO.stationId : ""
            }).then(res => {
              let idx = 0
              if (res.data.result.cardKindDTOList.length) {
                if (that.data.userInfo.firstMemberInfoCardDTO) {
                  res.data.result.cardKindDTOList.map((item, index) => {
                    if (item.productId == that.data.userInfo.firstMemberInfoCardDTO.productId) {
                      idx = index
                    }
                  })
                  that.data.productId = res.data.result.cardKindDTOList[idx].productId

                }
                res.data.result.distance = math.divide(res.data.result.distance, 1000).toFixed(2)
                that.setData({
                  station: res.data.result,
                  type_index: idx,
                  accountStoreCount: res.data.result.accountStoreCount,
                })
                that.getRechargeMenberCupPrice(that.data.station.id, that.data.productId, that.data.moneyList[0])
                wx.hideLoading()

                that.getActivityDetails()
              }
            })
          } else {
            api.getStoreOnMemberHome({
              lat: res.latitude,
              lot: res.longitude
            }).then(res => {
              if (res.data.result.cardKindDTOList.length > 0) {
                that.data.productId = res.data.result.cardKindDTOList[0].productId
              }
              that.setData({
                accountStoreCount: res.data.result.accountStoreCount,
                station: res.data.result
              })
              that.getRechargeMenberCupPrice(that.data.station.id, that.data.productId, that.data.moneyList[0])
              that.getActivityDetails()
              wx.hideLoading()
            })
          }
        },
        fail() {
          wx.hideLoading()
          wx.getSetting({
            success(res) {
              console.log(res)
              if (res.authSetting["scope.userLocation"] == false) {
                wx.showModal({
                  title: '提示',
                  content: '你的位置信息将用于小程序位置接口的效果展示',
                  showCancel: false,
                  success(res) {
                    if (res.confirm) {
                      wx.openSetting({
                        success(res) {}
                      })
                    }
                  }
                })
              } else {
                wx.showModal({
                  title: '提示',
                  content: '定位失败，请检查手机位置/定位是否打开',
                  showCancel: false
                })
              }
            }
          })
        }
      })
    },
    // 选择油品
    select(e) {
      this.setData({
        type_index: e.currentTarget.dataset.index
      })
      this.data.productId = this.data.station.cardKindDTOList[this.data.type_index].productId
      this.getActivityDetails()
      this.getRechargeMenberCupPrice(this.data.station.id, this.data.productId, this.data.moneyList[this.data.money_index])
    },
    // 选择金额
    money(e) {
      this.setData({
        money_index: e.currentTarget.dataset.index
      })
      this.getRechargeMenberCupPrice(this.data.station.id, this.data.productId, this.data.moneyList[this.data.money_index])
      this.getActivityDetails()
    },
    // 获取充值活动
    getActivityDetails() {
      let user = wx.getStorageSync('userInfo')
      let params = {
        activityType: "2",
        amount: this.data.moneyList[this.data.money_index] * 100,
        memberId: user ? user.id : "",
        orderSource: "1",
        productId: this.data.productId,
        storeId: this.data.station.id,
        payType: 2,
      }
      api.getActivityDetails(params).then(res => {
        this.data.couponIds = []
        this.data.serviceCardDTOList = []
        if (res.data.status == 200 && res.data.result.length) {
          this.data.discount = 0
          if (res.data.result[0].resultMap && res.data.result[0].resultMap.length) {
            res.data.result[0].resultMap.map(item => {
              this.data.discount
              item.money = math.divide(item.money, 100)
              item.money2 = math.times(item.money, item.num)
              this.data.discount = math.plus(this.data.discount, item.money2)
            })
          }
          if (res.data.result[0].couponList && res.data.result[0].couponList.length) {
            res.data.result[0].couponList.map(item => {
              this.data.couponIds.push(item.id)
            })
          }
          if (res.data.result[0].serviceCardDTOList && res.data.result[0].serviceCardDTOList.length) {
            res.data.result[0].serviceCardDTOList.map(item => {
              this.data.serviceCardDTOList.push(item.id)
            })

            console.log(this.data.serviceCardDTOList, "充值赠送的卡券看看！！！！！")
          }
          this.setData({
            rechargeActivity: res.data.result[0],
            discount: this.data.discount
          })

        } else {
          this.setData({
            rechargeActivity: null,
            discount: 0
          })
        }
      })
    },
    // 跳转更多站点
    go_stationList() {
      let memberId = wx.getStorageSync('userInfo')
      let id = memberId ? memberId.id:""
      let cityId = wx.getStorageSync('cityId')
      wx.navigateTo({
        url: '/pages/webView/webview?url=' + getApp().globalData.url + 'rechargeStationList&distanceInfo=' + JSON.stringify(this.data.distanceInfo) + '&memberId=' + id + '&cityId=' + cityId + '&companyId=' + this.data.station.companyId,
      })
    },
    // 创建充值订单
    createRechargeOrder(idempotenceToken) {
      let user = wx.getStorageSync('userInfo')
      if (!user) {
        var pages = getCurrentPages();
        var page = pages[pages.length - 1].route
        console.log(pages[pages.length - 1].route)

        wx.redirectTo({
          url: '/pages/login/login?page=' + page,
        })
        return false
      }
      wx.showLoading({
        title: '加载中...',
        mask: true
      })
      let activityId = ''
      let activityPositionId = ''
      if (this.data.rechargeActivity && this.data.rechargeActivity.activityId) {
        activityId = this.data.rechargeActivity.activityId
      }
      if (this.data.rechargeActivity && this.data.rechargeActivity.activityPositionId) {
        activityPositionId = this.data.rechargeActivity.activityPositionId
      }
      let memberCardId = ""
      if(this.data.memberCardProductId==this.data.productId){
        memberCardId = this.data.memberCardId
      }else{
        memberCardId = ""
      }
      let params = {
        memberId: user.id, //会员 ID
        memberCardId: memberCardId, // 会员卡 ID
        storeId: this.data.station.id,
        amount: math.times(this.data.moneyList[this.data.money_index], 100),
        payType: 2,
        source: "1",
        activityId: activityId,
        activityPositionId: activityPositionId,
        terminalId: this.data.station.rechargeTerminalId,
        productId: this.data.productId,
        couponIds: this.data.couponIds.toString(),
        serviceCardIds: this.data.serviceCardDTOList.toString(),
        companyId: this.data.station.companyId
      }
      if (!this.data.productId) {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '充值失败',
          showCancel: false
        })
        return false
      }
      api.createRechargeOrder(params, idempotenceToken).then(result => {
        this.wxPay(result)
      })
    },
    // 立即支付
    pay() {
      if (!this.data.bok) {
        return false
      }
      this.data.bok = false
      this.createRechargeOrder(this.data.idempotentToken)
    },
    // 微信预支付
    wxPay(res) {
      let openid = wx.getStorageSync('openid')
      let that = this
      let order = res.data.result.rechargeNumber
      api.pay({
        storeId: res.data.result.storeId,
        orderNumber: res.data.result.rechargeNumber,
        payAmount: res.data.result.amount,
        wxOpenId: openid,
        terminalId: res.data.result.terminalId
      }).then(res => {
        getApp().copyCityId()
        wx.requestPayment({
          timeStamp: res.data.result.timeStamp,
          nonceStr: res.data.result.nonceStr,
          package: res.data.result.package_str,
          signType: res.data.result.signType,
          paySign: res.data.result.paySign,
          success(res) {
            wx.hideLoading()
            that.data.bok = true
            wx.navigateTo({
              url: '/pages/paystatus/success/success?text=充值&money=' + that.data.moneyList[that.data.money_index] + '&price=' + that.data.discount + '&orderNumber=' + order
            })
          },
          fail(res) {
            wx.hideLoading()
            that.data.bok = true
            wx.showModal({
              title: '提示',
              content: '充值失败',
              showCancel: false,
              success(res) {

              }
            })
          }
        })
      })
    },
    getText() {
      api.getTextAdvert({}).then(res => {
        console.log(res.data.result, 'okokok')
        this.setData({
          text: res.data.result[0].name
        })
      })
    },
    pageInit() {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      this.drivingDistance()
      this.getText()
    }
  },
  observers: {
    'userInfo': function(val) {
      console.log(val)
      if (val&&val.id){
        var pages = getCurrentPages()
        var currentPage = pages[pages.length - 1]
        var url = currentPage.route
        getApp().login().then(res => {
          this.pageInit()
          let isIphoneX = getApp().globalData.isIphoneX
          this.setData({
            isIphoneX: isIphoneX,
            memberCardId: this.data.userInfo.firstMemberInfoCardDTO?this.data.userInfo.firstMemberInfoCardDTO.id:"",
            memberCardProductId: this.data.userInfo.firstMemberInfoCardDTO?this.data.userInfo.firstMemberInfoCardDTO.productId:""
          })
        })
      }else{
        var pages = getCurrentPages()
        var currentPage = pages[pages.length - 1]
        var url = currentPage.route
        getApp().login().then(res => {
          this.pageInit()
          let isIphoneX = getApp().globalData.isIphoneX
          this.setData({
            isIphoneX: isIphoneX,
          })
        })
      }
      
    }
  }
})